﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Gurucore.Framework.Core;
using Gurucore.Framework.Core.Util;
using Gurucore.Framework.Core.Activation;
using Gurucore.Framework.Core.Configuration;
using Gurucore.Framework.DataAccess.DataSource;
using Gurucore.Framework.DataAccess.DataProvider;
using Gurucore.Framework.DataAccess.Persistence;

namespace Gurucore.Framework.DataAccess
{
	public class DataAccessExtension : ExtensionBase
	{
		public override void Initialize(params object[] p_arrParam)
		{
			string sRootDir = Application.GetInstance().WorkingDirectory;
			string sConfigDir = sRootDir + Path.DirectorySeparatorChar + "Config";

			DataAccessConfiguration oDACfg = Application.GetInstance().GetGlobalSharedObject<DataAccessConfiguration>();

			//create table info manager
			TableInfoManager oTableInfoMgr = new TableInfoManager();
			Application.GetInstance().SetGlobalSharedObject(oTableInfoMgr);

			//create complex type manager
			ComplexTypeInfoManager oComplexTypeInfoMgr = new ComplexTypeInfoManager();
			Application.GetInstance().SetGlobalSharedObject(oComplexTypeInfoMgr);

			//load dataprovider factory
			DataProviderFactory oDPFactory = new DataProviderFactory(
                sConfigDir + Path.DirectorySeparatorChar + "System" + Path.DirectorySeparatorChar + "DataProvider.config");
			Application.GetInstance().SetGlobalSharedObject(oDPFactory);

			//load system's datasource factory
			DataSourceFactory oDSFactory = new DataSourceFactory(
                sConfigDir + Path.DirectorySeparatorChar + "System" + Path.DirectorySeparatorChar + "DataSource.config");
			//load all module's datasource factory
			DirectoryInfo oDirInfo = new DirectoryInfo(sConfigDir);
            FileInfo[] arrFile = oDirInfo.GetFiles("DataSource.config", SearchOption.AllDirectories);
			foreach (FileInfo oFile in arrFile)
			{
				if (!oFile.Directory.Name.EndsWith("System"))
				{
					DataSourceFactory oModuleDSFactory = new DataSourceFactory(oFile.FullName);
					oDSFactory.Merge(oModuleDSFactory);
				}
			}

			Application.GetInstance().SetGlobalSharedObject(oDSFactory);			
		}
	}
}
